var car =  {
   a: 1,
   b: 2
}
//监听属性变化
function defineReactive (obj, key ,val) {
    let dep = new Dep()
    Object.defineProperty(obj, key, {
        get () {
            console.log(`读取到${key}`)
            dep.depend()
            return val
        },
        set (newVal) {
            console.log(`修改了${key}`)
            dep.notify()
            val = newVal
        }
    })
}

//对对象的所有属性进行监听
function observable (obj) {
    if (!obj || typeof obj !== 'object') return 
    let keys = Object.keys(obj)
    keys.forEach(i => {
        defineReactive(obj, i, obj[i])
    })
}

class Watcher {
    constructor (vm, exp, cb) {
        this.vm = vm;
        this.exp = exp;
        this.cb = cb;
        this.value = this.get()
    } 
    update () {
        let value = this.vm.data[this.exp];
        let oldVal = this.value
        if (value !== oldVal) {
            this.value = value
            this.cb.call(this.vm, value, oldVal)
        }
    }
    get () {
        Dep.target = this; //缓存自己
        let value = this.vm.data[this.exp];
        Dep.target = null; //释放自己
        return value
    }
}

class Dep {
    constructor () {
        this.subs = []
    }
    //增加订阅者
    addSUb (sub) {
        this.subs.push(sub)
    }
    //判断是否增加订阅者
    depend () {
        if (Dep.target) {
            this.addSUb(Dep.target)
        }
    }
    //通知订阅者更新
    notify () {
        this.subs.forEach (sub => {
            sub.update()
        })
    }
}
Dep.target = null
